package com.sjb.mianshiya.backfilter;

import cn.hutool.bloomfilter.BitMapBloomFilter;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import lombok.Synchronized;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.yaml.snakeyaml.Yaml;

import java.util.List;
import java.util.Map;

/**
 * @Author:sjb
 * @CreateTime:2024-11-21
 * @Description: 黑名单过滤工具类
 * @Version：1.0
 */
@Slf4j
public class BlackIpUtils {

    private static BitMapBloomFilter bloomFilter;

    /**
     * 判断ip是否在黑名单内
     * @param ip
     * @return
     */
    public static boolean isBlackIp(String ip){
        return bloomFilter.contains(ip);
    }

    /**
     * 重建黑名单
     * @param configInfo
     */
    public static void rebuildBlackIp(String configInfo){
        if (StrUtil.isBlank(configInfo)){
            configInfo = "{}";
        }

        // 解析yaml文件
        Yaml yaml = new Yaml();
        Map yamlMap = yaml.loadAs(configInfo, Map.class);
        List<String> blackIpList =(List<String>) yamlMap.get("blackIpList");
        // 加锁防止并发
        synchronized (BlackIpUtils.class){
            if (CollectionUtil.isNotEmpty(blackIpList)){
                BitMapBloomFilter bitMapBloomFilter = new BitMapBloomFilter(958506);
                for (String blackIp : blackIpList) {
                    bitMapBloomFilter.add(blackIp);
                }
                bloomFilter = bitMapBloomFilter;
            }else {
                bloomFilter = new BitMapBloomFilter(100);
            }
        }
    }
}
